package wifiunion.com.notice.utils.db;

import android.content.Context;
import android.text.TextUtils;


import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

import java.util.List;

/**
 * Created by furan
 * 数据库管理类
 */
public class DBManager {
    private final static String DB_NAME = "intelligencecamera.db";
    private DbUtils mDBUtils;

    private static DBManager mInstance;
    public static DbUtils.DaoConfig config = null;
    public final static int DB_VERSIOIN = 3;


    private DBManager(Context context) {
        context = context.getApplicationContext();
        config = new DbUtils.DaoConfig(context);
        config.setDbName(DB_NAME);
        config.setDbVersion(DB_VERSIOIN);
        config.setDbUpgradeListener(dbUpgradeListener);

        // TODO 开发阶段先将数据库文件放到存储卡，上线时需要将此注释掉
//        config.setDbDir(Environment.getExternalStorageDirectory().getPath());
        mDBUtils = DbUtils.create(config);
        mDBUtils.configAllowTransaction(true);
        mDBUtils.configDebug(false);


    }

    DbUtils.DbUpgradeListener dbUpgradeListener = new DbUtils.DbUpgradeListener() {
        @Override
        public void onUpgrade(DbUtils dbUtil, int oldVersion,
                              int newVersion) {


            backupAndRecreateTable(dbUtil, PlaceInfo.class);
            backupAndRecreateTable(dbUtil, OrderStatus.class);
            backupAndRecreateTable(dbUtil, LocalPluginEntity.class);
//            // 数据库从版本1升级到版本2
//            if (oldVersion == 1 && (newVersion == 2 || newVersion == 3)) {
//                // DO SOMETHING
//                backupAndRecreateTable(dbUtil, PlaceInfo.class);
//            } else if (oldVersion == 2 && newVersion == 3) {
//                backupAndRecreateTable(dbUtil, PlaceInfo.class);
//            }
        }

    };

    public DbUtils getmDBUtils() {
        return mDBUtils;
    }


    /**
     * 备份原表数据，然后重新按照新的表结构创建新表，主要用于数据库升级的时候，添加表字段
     *
     * @param dbUtil
     * @param entityType
     */
    public static <T> void backupAndRecreateTable(DbUtils dbUtil,
                                                  Class<T> entityType) {
        try {
            List<T> list = dbUtil.findAll(entityType);
            // 先删除表再重新创建
            dbUtil.dropTable(entityType);
            if (list != null) {
                dbUtil.saveAll(list);
            } else {
                dbUtil.createTableIfNotExist(entityType);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public static DBManager getInstance(Context context) {

        if (mInstance == null) {
            synchronized (DBManager.class) {
                if (mInstance == null) {
                    mInstance = new DBManager(context);
                }
            }
        }
        return mInstance;
    }

    /************************************************用泛型重写了下增删改查 start**************************************************************************/
    public <T> boolean addInfo(T t) {

        boolean result = false;


        try {
            if (!mDBUtils.tableIsExist(t.getClass())) {
                mDBUtils.createTableIfNotExist(t.getClass());
            }
            result = mDBUtils.saveBindingId(t);
        } catch (DbException e) {
            e.printStackTrace();
        }

        return result;
    }


    public <T> void delInfo(T t) {

        try {
            if (!mDBUtils.tableIsExist(t.getClass())) {
                mDBUtils.createTableIfNotExist(t.getClass());
            }

            if (null != t) {
                mDBUtils.delete(t);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public <T> void updateInfo(T t) {

        try {
            if (!mDBUtils.tableIsExist(t.getClass())) {
                mDBUtils.createTableIfNotExist(t.getClass());
            }

            if (null != t) {
                mDBUtils.saveOrUpdate(t);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public <T> void getInfoRecord(Class<T> clazz, List<T> InfoList, Context context) {
        List<T> list = null;
        try {
            if (!mDBUtils.tableIsExist(clazz)) {
                mDBUtils.createTableIfNotExist(clazz);
            }


            list = mDBUtils.findAll(Selector.from(clazz).orderBy("id", true));
            if (null != list && list.size() > 0) {
                InfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }


    public <T> void getInfoRecordDEF(Class<T> clazz, List<T> InfoList, Context context) {
        List<T> list = null;
        try {
            if (!mDBUtils.tableIsExist(clazz)) {
                mDBUtils.createTableIfNotExist(clazz);
            }

            list = mDBUtils.findAll(Selector.from(clazz));
            if (null != list && list.size() > 0) {
                InfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }


    public <T> void getInfoList(Class<T> clazz, List<T> InfoList, Context context) {

        List<T> list = null;
        try {
            if (!mDBUtils.tableIsExist(clazz)) {
                mDBUtils.createTableIfNotExist(clazz);
            }

            list = mDBUtils.findAll(Selector.from(clazz).orderBy("id", true));

//            PlaceInfo placeInfo = new PlaceInfo();
//            placeInfo.setId(-1);
//            placeInfoList.add(placeInfo);
            if (null != list && list.size() > 0) {
                InfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }

    /**
     * 清除表数据
     */
    public <T> void delAll(Class<T> clazz) {
        try {
            if (!mDBUtils.tableIsExist(clazz)) {
                mDBUtils.createTableIfNotExist(clazz);
            }
            mDBUtils.deleteAll(clazz);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public <T> T findInfoByTag(Class<T> clazz,  String tag, String value) {
        T result = null;
        try {
            if (!mDBUtils.tableIsExist(clazz)) {
                mDBUtils.createTableIfNotExist(clazz);
            }

            result = mDBUtils.findFirst(Selector.from(clazz).where(tag, "=", value));

        } catch (DbException e) {
            e.printStackTrace();
        }
        return result;
    }


    /************************************************用泛型重写了下增删改查 end**************************************************************************/

    public void addPlaceInfo(PlaceInfo placeInfo) {
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }
            boolean result = mDBUtils.saveBindingId(placeInfo);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void delPlaceInfo(PlaceInfo placeInfo) {
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }

            if (null != placeInfo) {
                mDBUtils.delete(placeInfo);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void updatePlaceInfo(PlaceInfo placeInfo) {
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }

            if (null != placeInfo) {
                mDBUtils.saveOrUpdate(placeInfo);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    public void getPlaceInfoRecord(List<PlaceInfo> placeInfoList, Context context) {

        List<PlaceInfo> list = null;
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }


            list = mDBUtils.findAll(Selector.from(PlaceInfo.class).orderBy("id", true));
            if (null != list && list.size() > 0) {
                placeInfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }


    public void getPlaceInfoRecordDEF(List<PlaceInfo> placeInfoList, Context context) {

        List<PlaceInfo> list = null;
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }

            list = mDBUtils.findAll(Selector.from(PlaceInfo.class));
            if (null != list && list.size() > 0) {
                placeInfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }


    public void getPlaceInfoList(List<PlaceInfo> placeInfoList, Context context) {

        List<PlaceInfo> list = null;
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }

            list = mDBUtils.findAll(Selector.from(PlaceInfo.class).orderBy("id", true));

            PlaceInfo placeInfo = new PlaceInfo();
            placeInfo.setId(-1);
            placeInfoList.add(placeInfo);
            if (null != list && list.size() > 0) {
                placeInfoList.addAll(list);
            }
        } catch (DbException e) {
            e.printStackTrace();
//            Log.i("DBManager", "#######数据库异常#######");
        }

    }


    /**
     * 清除表数据
     */
    public void delAllPlaceInfo() {
        try {
            if (!mDBUtils.tableIsExist(PlaceInfo.class)) {
                mDBUtils.createTableIfNotExist(PlaceInfo.class);
            }
            mDBUtils.deleteAll(PlaceInfo.class);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    // ---------------PlaceInfo end--------


    // ---------------LocNoticeInfo Begin--------


    public void getLocNoticeInfoList(List<LocNoticeInfo> placeInfoList, Context context) {

        List<LocNoticeInfo> list = null;
        try {
            if (!mDBUtils.tableIsExist(LocNoticeInfo.class)) {
                mDBUtils.createTableIfNotExist(LocNoticeInfo.class);
            }
            list = mDBUtils.findAll(Selector.from(LocNoticeInfo.class));

        } catch (DbException e) {
            e.printStackTrace();

        }
    }


    public void saveOrupdateNotice(LocNoticeInfo info) {
        if (!TextUtils.isEmpty(info.getUuid())) {

            LocNoticeInfo temp = findLocNoticeInfoByUuid(info.getUuid());
            if (null != temp) {


                try {
                    if (!mDBUtils.tableIsExist(LocNoticeInfo.class)) {
                        mDBUtils.createTableIfNotExist(LocNoticeInfo.class);
                    }

                    temp.setSoundType(info.getSoundType());
                    temp.setSoundUrl(info.getSoundUrl());

                    mDBUtils.update(temp, WhereBuilder.b("id", "=", temp.getId()), "locnoticeinfo_soundtype", "locnoticeinfo_soundurl");
                } catch (DbException e) {
                    e.printStackTrace();
                }


            } else {


                try {
                    if (!mDBUtils.tableIsExist(LocNoticeInfo.class)) {
                        mDBUtils.createTableIfNotExist(LocNoticeInfo.class);
                    }
                    boolean result = mDBUtils.saveBindingId(info);
//                    Log.i("DBManager", "#######保存本地通知结果" + result);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }


        }


    }

    public LocNoticeInfo findLocNoticeInfoByUuid(String uuid) {
        LocNoticeInfo info = null;
        try {
            if (!mDBUtils.tableIsExist(LocNoticeInfo.class)) {
                mDBUtils.createTableIfNotExist(LocNoticeInfo.class);
            }

            info = mDBUtils.findFirst(Selector.from(LocNoticeInfo.class).where("locnoticeinfo_uuid", "=", uuid));

        } catch (DbException e) {
            e.printStackTrace();
        }
        return info;

    }

    /**
     * 删除本地通知
     *
     * @param uuid
     */
    public void delLocNoticeInfo(String uuid) {
        try {
            if (!mDBUtils.tableIsExist(LocNoticeInfo.class)) {
                mDBUtils.createTableIfNotExist(LocNoticeInfo.class);
            }
            mDBUtils.delete(LocNoticeInfo.class, WhereBuilder.b("locnoticeinfo_uuid", "=", uuid));

        } catch (DbException e) {
            e.printStackTrace();
        }
    }






}
